package com.cloud.model.entity;

public class ASTEvaluator {
    private final ASTNode root;
    private final ValueResolver resolver;

    // 构造函数，传入根节点和值解析器
    public ASTEvaluator(ASTNode root, ValueResolver resolver) {
        this.root = root;
        this.resolver = resolver;
    }

    // 评估表达式的最终结果
    public boolean evaluate() {
        return evaluateNode(root);
    }

    // 递归评估 AST 节点
    private boolean evaluateNode(ASTNode node) {
        if (node instanceof OperatorNode) {
            OperatorNode opNode = (OperatorNode) node;
            boolean left = evaluateNode(opNode.getLeft());
            boolean right = evaluateNode(opNode.getRight());
            
            // 根据操作符执行逻辑运算
            if ("AND".equals(opNode.getOperator())) {
                return left && right;
            } else if ("OR".equals(opNode.getOperator())) {
                return left || right;
            } else {
                throw new RuntimeException("Unknown operator: " + opNode.getOperator());
            }
        } else if (node instanceof ConditionNode) {
            ConditionNode condNode = (ConditionNode) node;

            // 从解析器获取对应字段的实际值
            String fieldValue = resolver.resolve(condNode.getField());
            String expectedValue = condNode.getValue().replace("'", ""); // 去掉引号
            String operator = condNode.getOperator();

            // 根据操作符执行比较
            if ("==".equals(operator)) {
                return expectedValue.equals(fieldValue);
            } else {
                throw new RuntimeException("Unknown operator: " + operator);
            }
        }
        throw new RuntimeException("Unknown AST node type");
    }
}